package org.jgs1904.tieba.controller;

import lombok.extern.slf4j.Slf4j;
import org.jgs1904.tieba.vo.CkImageUploadVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author junki
 * @date 2020/5/13 14:53
 */
@Controller
@Slf4j
public class FileUploadController {

    private final String imageFilePath = "F:/sbdemoupload/images/";

    @RequestMapping("images/ckupload")
    @ResponseBody
    public Object ckImageUpload(@RequestParam("upload") MultipartFile file, HttpServletRequest request) {
        log.info("开始上传图片");

        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 随机文件名
        String newFileName = UUID.randomUUID().toString() + suffixName;

        log.info("上传文件文件名称：{}", newFileName);
        log.info("上传文件大小 ：{}", file.getSize());

        // 判断路径是否存在
        File saveFile = new File(imageFilePath + newFileName);
        if (!saveFile.getParentFile().exists()) {
            saveFile.getParentFile().mkdirs();
        }

        // 保存文件
        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 获取当前http路径
        String contextUrl = request.getRequestURL().toString().replace("images/ckupload", "");

        // 返回vo实例
        return CkImageUploadVo.builder().uploaded(1).fileName(newFileName).url(contextUrl + newFileName).build();
    }

}

